package com.jack.helloworld.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.jack.helloworld.R;
import com.jack.helloworld.service.AppMonitorService;

import androidx.appcompat.app.AppCompatActivity;

public class RunningAppInfoActivity extends AppCompatActivity {

    private static final String TAG = "RunningAppInfoActivity";

    private TextView mRunningAppPackageName;

    private ServiceConnection mServiceConnection;
    private AppMonitorService mAppMonitorService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_app_info);

        mRunningAppPackageName = (TextView) findViewById(R.id.running_app_package_name);

        initData();
    }

    private void initData() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Toast.makeText(RunningAppInfoActivity.this, "onServiceConnected", Toast.LENGTH_SHORT).show();
                mAppMonitorService = ((AppMonitorService.AppMonitorBinderService)iBinder).getService();

                mAppMonitorService.setOnTopAppChangeListener(new AppMonitorService.OnTopAppChangeListener() {
                    @Override
                    public void onTopAppChange(String packageName) {
                        Log.e(TAG, "onTopAppChange");
                        Toast.makeText(RunningAppInfoActivity.this, "packageName:" + packageName, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Toast.makeText(RunningAppInfoActivity.this, "onServiceDisconnected", Toast.LENGTH_SHORT).show();
            }
        };


        Intent intent = new Intent(this, AppMonitorService.class);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
            mServiceConnection = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

}
